package com.neoCalf.neoCommon.utils;

import com.neoCalf.neoCommon.enums.ReadType;
import com.neoCalf.neoCommon.enums.ResultCode;
import com.neoCalf.neoCommon.exception.BusinessException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;


@Data
@Slf4j
public class ReadConfig {
    private static final Properties pro = new Properties();
    private static final Yaml yaml = new Yaml();
    private static Map<String, Object> dataMap = new ConcurrentHashMap<>();
    private final String dataSource;
    private final ReadType type;

    public ReadConfig(String dataSource, ReadType type) {
        this.dataSource = dataSource;
        this.type = type;
        init();
    }

    private void init() {
        InputStream fileInputStream = ReadConfig.class.getClassLoader().getResourceAsStream(dataSource);
        if (fileInputStream == null) {
            throw new RuntimeException("--加载配置文件失败--");
        }
        try {
            switch (type) {
                case PROPERTIES:
                    pro.load(new InputStreamReader(fileInputStream, StandardCharsets.UTF_8));
                    for (Object o : pro.keySet()) {
                        String key = (String) o;
                        dataMap.put(key, pro.getProperty(key));
                    }
                    break;
                case YML:
                    dataMap = yaml.load(fileInputStream);
                    break;
                default:
                    throw new BusinessException(ResultCode.BusinessError);
            }
        } catch (IOException e) {
            log.trace(e.getMessage());
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                log.trace(e.getMessage());
            }
        }
    }

    public String getValue(String key) {
        String s = (String) dataMap.get(key);
        if (s == null) {
            log.error("配置错误: {} 不存在", key);
            throw new RuntimeException();
        }
        return s;
    }

    public Integer getIntValue(String key) {
        return Integer.valueOf(getValue(key));
    }

    public long getLongValue(String key) {
        return Long.parseLong(getValue(key));
    }
}
